<?php
namespace bdhert\Tally\sign;

use bdhert\Tally\exception\SignException;
use bdhert\Tally\exception\SignOptionsException;
use bdhert\Tally\Signer;

/**
 * RSA验签
 * Class RSA
 * @package bdhert\Tally\sign
 */
class RSA extends Signer {
    public function check(string $sign_params, string $sign): bool {
        try {
            $public_key = file_get_contents($this->config['public_key']);

            if (false === ($public_key = openssl_pkey_get_public($public_key)))
                throw new SignOptionsException('证书配置错误', 500);
        } catch (\Exception $e) {
            throw new SignOptionsException('证书配置错误', 500);
        }

        $encrypted = str_replace(' ', '+', $sign);
        openssl_public_decrypt(base64_decode($encrypted), $decrypted, $public_key);
        if (empty($decrypted)) throw new SignException('验签错误', 500);

        return $sign_params === $decrypted;
    }
}